from models import execute, execute_with_commit


async def insert_address_by(uid, reciever, phone, area, address, is_default=False) -> int:
    sql = "INSERT INTO address(uid,name,phone,area,detail,is_default) values (%s,%s,%s,%s,%s,%s);"
    return await execute_with_commit(sql, (uid, reciever, phone, area, address, is_default))


async def get_id_is_default_by_uid(uid):
    sql = "select `id`,`is_default` from address where `uid`=%s;"
    return await execute(sql, (uid,))


async def update_addresses_set_not_default(uid):
    sql = "update address set is_default=0 where `uid`=%s;"
    return await execute_with_commit(sql, (uid,))


async def update_address_set_default(address_id):
    sql = "update address set is_default=1 where `id`=%s;"
    return await execute_with_commit(sql, (address_id,))


async def get_addresses_by_uid(uid):
    sql = "SELECT SQL_NO_CACHE id,name,phone,area,detail,is_default FROM address WHERE uid=%s ORDER BY is_default DESC ;"
    return await execute(sql, (uid,))


async def get_address_by_uid(uid):
    sql = "SELECT SQL_NO_CACHE id,name,phone,area,detail,is_default FROM address WHERE uid=%s ORDER BY is_default DESC LIMIT 1 ;"
    return await execute(sql, (uid,))


async def get_default_addresses_by_uid(uid):
    sql = "SELECT SQL_NO_CACHE id,name,phone,area,detail,is_default FROM address WHERE uid=%s AND is_default=1;"
    return await execute(sql, (uid,))


async def delete_address_by_id(id):
    sql = "DELETE FROM address WHERE id=%s;"
    return await execute_with_commit(sql, (id,))


async def update_address_by_id(address_id, receiver, mobile, area, address_detail, is_default):
    sql = "UPDATE address set `name`=%s,`phone`=%s,`area`=%s,`detail`=%s,is_default=%s where `id`=%s;"
    return await execute_with_commit(sql, (receiver, mobile, area, address_detail, is_default, address_id))
